package cn.com.tarotframework.exception;

import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintViolationCreationContext;
import org.hibernate.validator.internal.engine.path.NodeImpl;
import org.springframework.util.ObjectUtils;


import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * copyright (C), 2022, 塔罗牌基础架构
 *
 * @program: tarot-core
 * @author: xincan
 * @date: 2022/12/26 14:46
 * @version: 0.0.1-SNAPSHOT
 * @description: //TODO
 */
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {TarotParam.TarotParamValidator.class})
public @interface TarotParam {

    String name();
    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    // 指定多个时使用
    @Target({FIELD, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        TarotParam[] value();
    }


    class TarotParamValidator implements ConstraintValidator<TarotParam, Object> {

        private String name;

        @Override
        public void initialize(TarotParam tarotParam) {
            this.name = tarotParam.name();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            ConstraintViolationCreationContext a = ((ConstraintValidatorContextImpl) context).getConstraintViolationCreationContexts().get(0);
            NodeImpl node = a.getPath().getLeafNode();
            if(this.name.equals(node.getName()) && !ObjectUtils.isEmpty(value)) {
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        }

    }

}
